package com.sen.gulimall.product.web;

import com.sen.gulimall.product.entity.CategoryEntity;
import com.sen.gulimall.product.service.CategoryService;
import com.sen.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: IndexController
 * @Title: gulimall
 * @Package: com.sen.gulimall.product.web
 * @Description:
 * @Author: Kisen
 * @Date: 2022/3/22 16:38
 */
@Controller
public class IndexController {

    public static final String REDIS_LOCK_KEY = "redis-lock";

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redisson;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {

        //TODO 1、查出所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();

        // 试图解析器进行拼串
        // classpath:/templates/ + 返回值 + .html
        model.addAttribute("categorys", categoryEntities);
        return "index.html";
    }

    //index/catalog.json
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    @ResponseBody
    @GetMapping("buyGoods")
    public String buyGoods() {
        //1、占redis分布式锁，加锁（SETNX和设置过期时间）保证原子性
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(REDIS_LOCK_KEY, uuid, 30, TimeUnit.SECONDS);
        if (lock) {
            try {
                //更难的事情：锁的自动续期

                System.out.println("获取分布式锁成功，执行业务...");
                //商品扣库存
                String stock = redisTemplate.opsForValue().get("goods:001");
                if (stock == null || Integer.parseInt(stock) <= 0) {
                    return "商品已经售罄，欢迎下次光临!";
                }
                int leftStock = Integer.parseInt(stock) - 1;
                redisTemplate.opsForValue().set("goods:001", String.valueOf(leftStock));
                return "商品购买成功，剩余库存" + leftStock + "（件）";

            } finally {
                //2、释放锁（删除自己的锁）保证原子性
                //1.lua脚本保证原子性（推荐）
                String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long result = redisTemplate.execute(new DefaultRedisScript<>(luaScript, Long.class),
                        Arrays.asList(REDIS_LOCK_KEY), uuid);

                /*//2.redis事务保证原子性
                while (true) {
                    //事务，乐观锁
                    redisTemplate.watch(REDIS_LOCK_KEY);
                    //判断是否是自己加的锁
                    if (uuid.equals(redisTemplate.opsForValue().get(REDIS_LOCK_KEY))) {
                        //开启事务
                        redisTemplate.setEnableTransactionSupport(true);
                        redisTemplate.multi();
                        redisTemplate.delete(REDIS_LOCK_KEY);
                        //判断事务是否执行成功，如果等于 null，就是没有删掉，删除失败，再回去 while 循环那再重新执行删除
                        List<Object> exec = redisTemplate.exec();
                        if (exec == null) {
                            continue;
                        }
                    }
                    //如果删除成功，释放监控器，并且 break 跳出当前循环
                    redisTemplate.unwatch();
                    break;
                }*/
            }
        }

        return "服务器繁忙，请勿频繁操作！";
    }

    @ResponseBody
    @GetMapping("hello")
    public String hello() {
        //1、获取一把锁，只要锁的名字一样，就是同一把锁
        RLock lock = redisson.getLock("my-lock");

        //2、加锁
//        lock.lock();//阻塞式等待。默认加的锁都是30s时间。
        //1）、锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s。不用担心业务时间长，锁自动过期被删掉
        //2）、加锁的业务只要运行完成，就不会给当前锁续期，即使不手动解锁，锁默认在30s以后自动删除。

        lock.lock(10, TimeUnit.SECONDS); //10秒自动解锁，自动解锁时间一定要大于业务的执行时间。
        //问题：lock.lcok(10, Timeunit.SECONDS);在锁时间到了以后，不会自动续期。
        //1、如果我们传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是我们指定的时间
        //2、如果我们未指定锁的超时时间，就使用30000【lockWatchdogTimeout看门狗的默认时间】;
        //      只要占锁成功，就会启动一个定时任务【重新给锁设置过期时间，新的过期时间就是看门狗的默认时间】，每隔10s都会自动再次续期，续成30s
        //      internalLockLeaseTime【看门狗时间】 / 3L, TimeUnit.MILLISECONDS

        //最佳实战
        //1）、lock.lock(30, TimeUnit.SECONDS);省掉了整个续期操作。手动解锁
        try {
            System.out.println("加锁成功，执行业务..." + Thread.currentThread().getId());
            TimeUnit.SECONDS.sleep(30);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //3、解锁  假设解锁代码没有运行，redisson不会出现死锁
            System.out.println("释放锁..." + Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }

    //保证一定能读到最新数据，修改期间，写锁是一个排他锁（互斥锁、独享锁）。读锁是一个共享锁
    //写锁没释放读就必须等待
    //读 + 读：相当于无锁，并发读，只会在redis中记录好，所有当前的读锁。他们都会同时加锁成功
    //写 + 读：等待写锁释放
    //写 + 写：阻塞方式
    //读 + 写：有读锁，写也需要等待。
    // 只要有写的存在，都必须等待
    @GetMapping("write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        //1、改数据加写锁，读数据加读锁
        rLock.lock();
        String s;
        try {
            System.out.println("写锁加锁成功..." + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            TimeUnit.SECONDS.sleep(30);
            redisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            rLock.unlock();
            System.out.println("写锁释放" + Thread.currentThread().getId());
        }

        return s;
    }

    @GetMapping("read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
//        ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

        //加读锁
        RLock rLock = lock.readLock();
        rLock.lock();
        String s;
        try {
            System.out.println("读锁加锁成功..." + Thread.currentThread().getId());
            TimeUnit.SECONDS.sleep(30);
            s = redisTemplate.opsForValue().get("writeValue");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            rLock.unlock();
            System.out.println("读锁释放" + Thread.currentThread().getId());
        }

        return s;
    }

    /**
     * 车库停车
     * 3车位
     * 信号量也可以用作分布式限流；
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
//        park.acquire();//获取一个信号，获取一个值，占一个车位
        boolean b = park.tryAcquire();
        if (b) {
            //执行业务
            return "ok=>" + b;
        }

        return "error";
    }

    @GetMapping("go")
    @ResponseBody
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();//释放一个车位

//        Semaphore semaphore = new Semaphore(5);
//        semaphore.release();
//        semaphore.acquire();

        return "ok";
    }

    /**
     * 放假，锁门
     * 5个班全部走完，我们可以锁大门
     *
     * @return
     * @throws InterruptedException
     */
    @GetMapping("lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁都完成

//        CountDownLatch countDownLatch = new CountDownLatch(5);
//        countDownLatch.await();
//        countDownLatch.countDown();

        return "放假了...";
    }

    @GetMapping("gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id) {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();//计数减一

        return id + "班的人都走了";
    }
}
